package com.four.controller;

import com.alibaba.excel.EasyExcel;
import com.four.entity.Reg;
import com.four.service.RegService;
import com.four.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: WangPeng
 * @createTime: 2022/10/22 18:23
 * @description:
 * @version: v1.0
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private RegService regService;

    @RequestMapping ("download")
    public void download(HttpServletResponse response,Integer regId ) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        Date date = new Date();
        String fileName = URLEncoder.encode("病历详情"+new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        Result result = regService.selectByRegId(regId);
        ArrayList<Reg> list = new ArrayList<>();
        list.add((Reg)result.getData());
        EasyExcel.write(response.getOutputStream(), Reg.class).sheet("模板").doWrite(list);
        System.out.println("12345");
    }
}
